package io.lkt.modules.sys.controller;

import io.lkt.common.util.Query;
import io.lkt.common.utils.*;
import io.lkt.common.validator.ValidatorUtils;
import io.lkt.modules.sys.entity.*;
import io.lkt.modules.sys.service.KeywordInfoService;
import io.lkt.modules.sys.service.PushHeadLogService;
import io.lkt.modules.sys.service.PythonArticleInfoService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/sys/pushheadlog")
public class PushHeadLogController extends AbstractController{
    @Autowired
    private PushHeadLogService pushHeadLogService;

    @Autowired
    private KeywordInfoService keywordInfoService;

    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = pushHeadLogService.queryPage(params);
        return R.ok().put("page", page);
    }

    @RequestMapping("/queryList")
    public R queryList(@RequestParam Map<String, Object> params) throws ParseException {
        if(params.get("gzhCode") == null || params.get("gzhCode").toString().trim().equals("")) {
            return R.ok();
        }

        String gzhCode = params.get("gzhCode").toString();// 公众号
        String startKeyWordDate = "";// 开始日期：回复关键词
        String endKeyWordDate = "";// 结束日期：回复关键词

        if(params.get("startDate")!=null && !params.get("startDate").toString().trim().equals("")) {

            String startDate= params.get("startDate").toString();
            params.put("startDate", startDate); //今天开始时间
            params.put("endDate", startDate+" 23:59:59"); //今天结束时间

            SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd" );
            Date date = sdf.parse( startDate);

            String yesterday=DateUtilPlus.formatDate(DateUtilPlus.getYesterday(date));
            params.put("startYesterDay", yesterday); //昨天开始时间
            params.put("endYesterDay", yesterday+" 23:59:59"); //昨天结束时间

            String lastWeekToDay=DateUtilPlus.formatDate(DateUtilPlus.getToDayOfLastWeek(date));
            params.put("startLastWeekToDay", lastWeekToDay); //上周同期开始时间
            params.put("endLastWeekToDay", lastWeekToDay+" 23:59:59"); //上周同期结束时间

            String lastWeekFirstDay=DateUtilPlus.formatDate(DateUtilPlus.getFirstDayOfLastWeek(date));
            params.put("startLastWeekFirstDay", lastWeekFirstDay); //上周开始时间
            String lastWeekLastDay=DateUtilPlus.formatDate(DateUtilPlus.getLastDayOfLastWeek(date));
            params.put("endLastWeekLastDay", lastWeekLastDay+" 23:59:59"); //上周结束时间

            String lastMonthFirstDay=DateUtilPlus.formatDate(DateUtilPlus.getFirstDayOfLastMonth(date));
            params.put("startLastMonthFirstDay", lastMonthFirstDay); //上月开始时间
            String lastMonthLastDay=DateUtilPlus.formatDate(DateUtilPlus.getLastDayOfLastMonth(date));
            params.put("endLastMonthLastDay", lastMonthLastDay+" 23:59:59"); //上月结束时间

            // 48小时前的日期
            startKeyWordDate = sdf.format(DateUtils.addHours(date, -48));
            endKeyWordDate = startDate;
            System.out.println("48小时前的日期：[startKeyWordDate] = " + startKeyWordDate);
        }
//        if(params.get("endDate")!=null && !params.get("endDate").toString().trim().equals("")) {
//            params.put("endDate", params.get("endDate")+" 23:59:59");
//        }

        Query query = new Query(params);
        List<PushHeadLogEntity> list=pushHeadLogService.queryList(query);
        if (CollectionUtils.isNotEmpty(list)) {
            for(PushHeadLogEntity entity : list) {
                int msgType = entity.getMsgType().intValue();
                String typeDate = "";

                if (msgType == 1) { // 早上6点
                    typeDate = " 06:00:00";
                } else if (msgType == 2) { // 早上8点
                    typeDate = " 08:00:00";
                } else if (msgType == 3) { // 上午11点
                    typeDate = " 11:00:00";
                } else if (msgType == 4) { // 下午6点
                    typeDate = " 18:00:00";
                } else if (msgType == 5) { // 晚上9点
                    typeDate = " 21:00:00";
                } else if (msgType == 7) { // 上午9点半
                    typeDate = " 09:30:00";
                } else if (msgType == 8) { // 晚上20点
                    typeDate = " 20:00:00";
                } else if (msgType == 17) { // 下午5点
                    typeDate = " 17:00:00";
                }

                PushHeadLogEntity pushHeadLogEntity = keywordInfoService.getUserCount(gzhCode, startKeyWordDate + typeDate, endKeyWordDate + typeDate, entity.getId());
                entity.setInputKeywordUserCount(pushHeadLogEntity.getInputKeywordUserCount());
                entity.setIntersectionUserCount(pushHeadLogEntity.getIntersectionUserCount());
                DecimalFormat df = new DecimalFormat("#.00");
                entity.setRateOfSuccess(df.format((pushHeadLogEntity.getIntersectionUserCount().doubleValue()/pushHeadLogEntity.getInputKeywordUserCount())*100)+"%");

                entity.setClickArticleUserCount(pushHeadLogEntity.getClickArticleUserCount());
                entity.setClickArticleSingleUserCount(pushHeadLogEntity.getClickArticleSingleUserCount());
                entity.setClickArticleSingleIntersectionCount(pushHeadLogEntity.getClickArticleSingleIntersectionCount());
                entity.setClickarticleRateOfSuccess(df.format((pushHeadLogEntity.getClickArticleSingleIntersectionCount().doubleValue()/pushHeadLogEntity.getIntersectionUserCount())*100)+"%");
            }
        }
        int total = pushHeadLogService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(list, total, query.getLimit(), query.getPage());
        return R.ok().put("page",pageUtil);
    }


    @RequestMapping("/queryMainPage")
    public R queryMainPage(@RequestBody Map<String, Object> params) {

        String startDate = DateUtil.getFormatDate("yyyy-MM-dd", new Date());
        String endDate = DateUtil.getFormatDate("yyyy-MM-dd", new Date()) + " 23:59:59";

        if (params.get("pDate") != null) {
            startDate = params.get("pDate").toString();
            endDate = params.get("pDate").toString() + " 23:59:59";
        }
        params.put("startDate", startDate);
        params.put("endDate", endDate);

        Map<String, Object> rMap=new HashMap<>();

        List<PushHeadLogEntity> list = pushHeadLogService.queryVital(params);
        PushHeadLogEntity ove = null;
        if (list != null && list.size() > 0) {
            for (PushHeadLogEntity phl : list) {
                if (phl.getMsgType().equals(1)) {
                    rMap.put("t6",phl.getSuccessCount());
                } else if (phl.getMsgType().equals(2)) {
                    rMap.put("t8",phl.getSuccessCount());
                } else if (phl.getMsgType().equals(7)) {
                    rMap.put("t9",phl.getSuccessCount());
                } else if (phl.getMsgType().equals(3)) {
                    rMap.put("t11",phl.getSuccessCount());
                } else if (phl.getMsgType().equals(17)) {
                    rMap.put("t17",phl.getSuccessCount());
                }else if (phl.getMsgType().equals(4)) {
                    rMap.put("t18",phl.getSuccessCount());
                }else if (phl.getMsgType().equals(8)) {
                    rMap.put("t20",phl.getSuccessCount());
                }else if (phl.getMsgType().equals(5)) {
                    rMap.put("t21",phl.getSuccessCount());
                }
            }
        }

        return R.ok().put("vital", rMap);
    }

    /**
     * 根据 ID 获取推送消息日志的头信息
     * @param id
     * @return
     */
    @RequestMapping("/{id}")
    public R queryById(@PathVariable Integer id) {
        if (id == null) {
            return R.error("访问失败！");
        }
        PushHeadLogEntity pushHeadLog = pushHeadLogService.queryById(id);
        return R.ok().put("pushHeadLog", pushHeadLog);
    }

    @RequestMapping("/detail")
    public R queryDetailById(@RequestParam Map<String, Object> params) {
        if (params.get("id") == null) {
            return R.error("访问失败！");
        }
        PageUtils page = pushHeadLogService.getDetailById(params);
        return R.ok().put("page", page);
    }

}
